package com.christina.service;

import com.christina.engine.observer.EventManager;
import com.christina.engine.singleton.ConfigurationManager;
import com.christina.engine.state.ConversationStateManager;
import com.christina.engine.processing.RequestProcessorChain;
import com.christina.engine.strategy.RoutingStrategyManager;
import com.christina.engine.factory.ServiceExecutorFactory;
import com.christina.engine.parameter.builder.ParameterBuilderFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 设计模式验证服务
 * 在应用启动时验证所有设计模式的集成状态
 * 
 * @author Christina
 */
@Slf4j
@Service
public class DesignPatternValidationService {

    private final EventManager eventManager;
    private final ConversationStateManager conversationStateManager;
    private final RequestProcessorChain requestProcessorChain;
    private final RoutingStrategyManager routingStrategyManager;
    private final ServiceExecutorFactory serviceExecutorFactory;
    private final ParameterBuilderFactory parameterBuilderFactory;
    private final ConfigurationManager configurationManager;

    @Autowired
    public DesignPatternValidationService(
            EventManager eventManager,
            ConversationStateManager conversationStateManager,
            RequestProcessorChain requestProcessorChain,
            RoutingStrategyManager routingStrategyManager,
            ServiceExecutorFactory serviceExecutorFactory,
            ParameterBuilderFactory parameterBuilderFactory) {
        this.eventManager = eventManager;
        this.conversationStateManager = conversationStateManager;
        this.requestProcessorChain = requestProcessorChain;
        this.routingStrategyManager = routingStrategyManager;
        this.serviceExecutorFactory = serviceExecutorFactory;
        this.parameterBuilderFactory = parameterBuilderFactory;
        this.configurationManager = ConfigurationManager.getInstance();
    }

    /**
     * 应用启动完成后执行验证
     */
    @EventListener(ApplicationReadyEvent.class)
    public void validateDesignPatterns() {
        log.info("开始验证设计模式集成状态...");
        
        Map<String, ValidationResult> results = new HashMap<>();
        
        // 验证各个设计模式
        results.put("观察者模式", validateObserverPattern());
        results.put("单例模式", validateSingletonPattern());
        results.put("状态模式", validateStatePattern());
        results.put("责任链模式", validateChainOfResponsibilityPattern());
        results.put("策略模式", validateStrategyPattern());
        results.put("工厂模式", validateFactoryPattern());
        results.put("建造者模式", validateBuilderPattern());
        
        // 输出验证结果
        printValidationResults(results);
        
        // 记录整体状态
        boolean allValid = results.values().stream().allMatch(ValidationResult::isValid);
        if (allValid) {
            log.info("✅ 所有设计模式验证通过！系统已准备就绪。");
            configurationManager.setConfiguration("validation.design-patterns.status", "PASSED");
        } else {
            log.warn("⚠️ 部分设计模式验证失败，请检查系统配置。");
            configurationManager.setConfiguration("validation.design-patterns.status", "FAILED");
        }
        
        configurationManager.setConfiguration("validation.design-patterns.timestamp", 
                System.currentTimeMillis());
    }

    /**
     * 验证观察者模式
     */
    private ValidationResult validateObserverPattern() {
        try {
            // 检查事件管理器
            if (eventManager == null) {
                return ValidationResult.failed("EventManager未初始化");
            }
            
            // 检查监听器数量
            int listenerCount = eventManager.getAllListeners().size();
            if (listenerCount < 2) {
                return ValidationResult.failed("监听器数量不足: " + listenerCount);
            }
            
            // 检查统计信息
            Map<String, Object> stats = eventManager.getStatistics();
            if (stats == null || stats.isEmpty()) {
                return ValidationResult.failed("事件统计信息不可用");
            }
            
            return ValidationResult.passed("监听器数量: " + listenerCount);
            
        } catch (Exception e) {
            return ValidationResult.failed("验证异常: " + e.getMessage());
        }
    }

    /**
     * 验证单例模式
     */
    private ValidationResult validateSingletonPattern() {
        try {
            // 检查配置管理器单例
            if (configurationManager == null) {
                return ValidationResult.failed("ConfigurationManager未初始化");
            }
            
            // 验证单例特性
            ConfigurationManager instance1 = ConfigurationManager.getInstance();
            ConfigurationManager instance2 = ConfigurationManager.getInstance();
            if (instance1 != instance2) {
                return ValidationResult.failed("单例模式失效");
            }
            
            // 检查配置数量
            Map<String, Object> configs = configurationManager.getAllConfigurations();
            if (configs == null) {
                return ValidationResult.failed("配置信息不可用");
            }
            
            return ValidationResult.passed("配置项数量: " + configs.size());
            
        } catch (Exception e) {
            return ValidationResult.failed("验证异常: " + e.getMessage());
        }
    }

    /**
     * 验证状态模式
     */
    private ValidationResult validateStatePattern() {
        try {
            // 检查状态管理器
            if (conversationStateManager == null) {
                return ValidationResult.failed("ConversationStateManager未初始化");
            }
            
            // 检查状态管理器统计
            Map<String, Object> stats = conversationStateManager.getStatistics();
            if (stats == null) {
                return ValidationResult.failed("状态统计信息不可用");
            }
            
            return ValidationResult.passed("状态管理器正常运行");
            
        } catch (Exception e) {
            return ValidationResult.failed("验证异常: " + e.getMessage());
        }
    }

    /**
     * 验证责任链模式
     */
    private ValidationResult validateChainOfResponsibilityPattern() {
        try {
            // 检查处理器链
            if (requestProcessorChain == null) {
                return ValidationResult.failed("RequestProcessorChain未初始化");
            }
            
            // 检查处理器数量
            if (!requestProcessorChain.isEnabled()) {
                return ValidationResult.failed("处理器链未启用");
            }
            
            int processorCount = requestProcessorChain.getProcessorCount();
            if (processorCount < 5) {
                return ValidationResult.failed("处理器数量不足: " + processorCount);
            }
            
            return ValidationResult.passed("处理器数量: " + processorCount);
            
        } catch (Exception e) {
            return ValidationResult.failed("验证异常: " + e.getMessage());
        }
    }

    /**
     * 验证策略模式
     */
    private ValidationResult validateStrategyPattern() {
        try {
            // 检查路由策略管理器
            if (routingStrategyManager == null) {
                return ValidationResult.failed("RoutingStrategyManager未初始化");
            }
            
            // 检查策略数量
            int strategyCount = routingStrategyManager.getStrategyCount();
            if (strategyCount < 2) {
                return ValidationResult.failed("策略数量不足: " + strategyCount);
            }
            
            return ValidationResult.passed("策略数量: " + strategyCount);
            
        } catch (Exception e) {
            return ValidationResult.failed("验证异常: " + e.getMessage());
        }
    }

    /**
     * 验证工厂模式
     */
    private ValidationResult validateFactoryPattern() {
        try {
            // 检查服务执行器工厂
            if (serviceExecutorFactory == null) {
                return ValidationResult.failed("ServiceExecutorFactory未初始化");
            }
            
            // 检查支持的服务类型
            String[] requiredServices = {"ChatDomainService", "TravelDomainService", "UserDomainService"};
            for (String service : requiredServices) {
                if (!serviceExecutorFactory.supportsService(service)) {
                    return ValidationResult.failed("不支持服务: " + service);
                }
            }
            
            return ValidationResult.passed("支持所有必需服务");
            
        } catch (Exception e) {
            return ValidationResult.failed("验证异常: " + e.getMessage());
        }
    }

    /**
     * 验证建造者模式
     */
    private ValidationResult validateBuilderPattern() {
        try {
            // 检查参数建造者工厂
            if (parameterBuilderFactory == null) {
                return ValidationResult.failed("ParameterBuilderFactory未初始化");
            }
            
            // 检查支持的类型
            Class<?>[] requiredTypes = {
                com.christina.service.domain.travel.model.TravelPlanRequest.class,
                com.christina.service.domain.chat.model.ChatRequest.class
            };
            
            for (Class<?> type : requiredTypes) {
                if (!parameterBuilderFactory.supportsType(type)) {
                    return ValidationResult.failed("不支持类型: " + type.getSimpleName());
                }
            }
            
            return ValidationResult.passed("支持所有必需类型");
            
        } catch (Exception e) {
            return ValidationResult.failed("验证异常: " + e.getMessage());
        }
    }

    /**
     * 打印验证结果
     */
    private void printValidationResults(Map<String, ValidationResult> results) {
        log.info("==================== 设计模式验证结果 ====================");
        
        results.forEach((pattern, result) -> {
            String status = result.isValid() ? "✅ 通过" : "❌ 失败";
            log.info("{}: {} - {}", pattern, status, result.getMessage());
        });
        
        log.info("========================================================");
        
        // 统计结果
        long passedCount = results.values().stream().mapToLong(r -> r.isValid() ? 1 : 0).sum();
        long totalCount = results.size();
        
        log.info("验证统计: {}/{} 通过", passedCount, totalCount);
        
        if (passedCount == totalCount) {
            log.info("🎉 恭喜！所有设计模式都已正确集成！");
        } else {
            log.warn("⚠️ 有 {} 个设计模式需要修复", totalCount - passedCount);
        }
    }

    /**
     * 获取验证状态
     */
    public Map<String, Object> getValidationStatus() {
        Map<String, Object> status = new HashMap<>();
        
        status.put("status", configurationManager.getString("validation.design-patterns.status", "UNKNOWN"));
        status.put("timestamp", configurationManager.getLong("validation.design-patterns.timestamp", 0L));
        
        // 添加各组件状态
        status.put("components", Map.of(
                "eventManager", eventManager != null ? "AVAILABLE" : "UNAVAILABLE",
                "configurationManager", configurationManager != null ? "AVAILABLE" : "UNAVAILABLE",
                "conversationStateManager", conversationStateManager != null ? "AVAILABLE" : "UNAVAILABLE",
                "requestProcessorChain", requestProcessorChain != null ? "AVAILABLE" : "UNAVAILABLE",
                "routingStrategyManager", routingStrategyManager != null ? "AVAILABLE" : "UNAVAILABLE",
                "serviceExecutorFactory", serviceExecutorFactory != null ? "AVAILABLE" : "UNAVAILABLE",
                "parameterBuilderFactory", parameterBuilderFactory != null ? "AVAILABLE" : "UNAVAILABLE"
        ));
        
        return status;
    }

    /**
     * 验证结果内部类
     */
    private static class ValidationResult {
        private final boolean valid;
        private final String message;

        private ValidationResult(boolean valid, String message) {
            this.valid = valid;
            this.message = message;
        }

        public static ValidationResult passed(String message) {
            return new ValidationResult(true, message);
        }

        public static ValidationResult failed(String message) {
            return new ValidationResult(false, message);
        }

        public boolean isValid() {
            return valid;
        }

        public String getMessage() {
            return message;
        }
    }
}